package org.jlamp.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jlamp.core.prop.JlampFileProp;
import org.jlamp.core.prop.SystemProp;

import java.io.*;

/**
 * @author zhangcs
 * @since 1.0
 */
public class JlampUtils {

    /**
     * Jlamp根路径
     */
    private static String JLAMP_HOME_DIR;

    /**
     * 日志文件路径
     */
    private static String LOG_PATH;

    /**
     * 日志记录对象
     */
    private static PrintStream logger;

    /**
     * 获取Home目录
     *
     * @return 返回绝对路径
     */
    public static String home() {
        // 进程ID
        String id = ProcessInfoUtils.id();
        return home(id);
    }

    /**
     * 获取Home目录
     *
     * @param id 进程号
     * @return 返回绝对路径
     */
    public static String home(String id) {
        String relative = File.separator + JlampFileProp.JLAMP_HOME_DIR_NAME + File.separator + id + File.separator;
        File homeDir = new File(SystemProp.USER_HOME + relative);
        if (!homeDir.exists()) {
            // home 路径下创建
            homeDir.mkdirs();
        }

        if (!homeDir.exists()) {
            // tmp 路径下创建
            homeDir = new File(SystemProp.TMP_DIR + relative);
            if (!homeDir.exists()) {
                homeDir.mkdirs();
            }
        }

        if (!homeDir.exists()) {
            //
        }

        // jlamp home 绝对路径
        String path = homeDir.getAbsolutePath();

        JLAMP_HOME_DIR = path;
        return path;
    }

    /**
     * 获取日志记录对象
     *
     * @return 返回日志输出流
     */
    public static PrintStream logger() {
        if (logger != null) {
            return logger;
        }

        try {
            String path = JLAMP_HOME_DIR;
            if (path == null || path.length() <= 0) {
                home();
            }

            // 日志文件
            File log = new File(path, JlampFileProp.JLAMP_LOG_FILE_NAME);
            if (!log.exists()) {
                log.createNewFile();
            }
            LOG_PATH = log.getAbsolutePath();

            logger = new PrintStream(new FileOutputStream(log, true));
            return logger;
        } catch (Exception e) {
            // ignore
        }
        return System.err;
    }

    /**
     * 日志文件路径
     *
     * @return 返回日志文件绝对路径
     */
    public static String logPath() {
        if (LOG_PATH != null) {
            return LOG_PATH;
        }

        logger();

        return LOG_PATH;
    }

    /**
     * 记录当前使用的端口信息
     *
     * @param port 端口号
     */
    public static void port(int port) {
        String home = home();
        try {
            File file = new File(home + File.separator + JlampFileProp.JLAMP_DATA_FILE_NAME);
            if (!file.exists()) {
                // home 路径下创建
                file.createNewFile();
            }

            if (!file.exists()) {
                throw new RuntimeException("Open data file '" + file.getAbsolutePath() + "' failed");
            }

            // 读文件
            JSONObject obj = read(file);

            obj.put("port", port);

            // 写文件
            write(obj, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static JSONObject read(File file) throws IOException {
        FileReader reader = new FileReader(file);

        StringBuilder sb = new StringBuilder();
        char[] buf = new char[1024];
        while ((reader.read(buf)) != -1) {
            sb.append(buf);
        }

        reader.close();

        String json = sb.toString();
        if (json.length() <= 0) {
            return new JSONObject();
        }
        return JSON.parseObject(json);
    }

    private static void write(JSONObject obj, File file) throws IOException {
        String json = obj.toJSONString();

        FileWriter writer = new FileWriter(file);
        writer.write(json);
        writer.flush();
        writer.close();
    }

}
